package com.fruit.interceptor;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fruit.common.CookieUtil;
import com.fruit.util.ResultInfo;
import com.fruit.util.ResultUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 微信(登录确认页与关联页面)登录拦截器
 * 
 * @author Administrator
 * @version 2018.02.02 12:40
 */
@Slf4j
public class WeChatWapSecurityInterceptor extends HandlerInterceptorAdapter {
	@Value("${h5_domain}")
	private String h5Domain;
	@Value("${domain}")
	private String domain;
	@Value("${top_domain}")
	private String topDomain;
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		log.info("登录拦截处理-----开始");
		response.setContentType("text/html;charset=UTF-8");
		String ua = ((HttpServletRequest) request).getHeader("user-agent");
		if (StringUtils.isEmpty(ua)) {
			return false;
		}
		String requestType = request.getHeader("X-Requested-With");
		String forward = request.getParameter("forward");
		log.info("参数：forward={}", forward);
		String contextPath = request.getContextPath();
		String openId = CookieUtil.getValue(request, "publicOpenid");
		log.info("微信浏览器----开始openid={}", openId);
		if (StringUtils.isEmpty(openId)) { //没有 回登录
			if (!StringUtils.equals(requestType, "XMLHttpRequest")) {
				if (StringUtils.isEmpty(forward)) {
					response.sendRedirect(contextPath + "/wap/login/toLogin");
				} else {
					response.sendRedirect(contextPath + "/wap/login/toLogin?forward=" + forward +"&sourceChannel=0");
				}
			} else {
				Map<String, Object> resMap = new HashMap<String, Object>();
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "loginOut", "用户未登录", "/toLogin"));
				ObjectMapper om = new ObjectMapper();
				response.getWriter().print(om.writeValueAsString(resMap));
			}
			return false;
		}
		return true;
	}
}
